package com.kbbywyclient.util;

import android.graphics.Bitmap;
import android.support.annotation.NonNull;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Jiangzx on 2017/8/19 11:33.
 */

public class QrCodeUtils {
    /**
     * 生成一个二维码
     * @param content 二维码内容
     * @param qrCodeWidth 二维码宽度
     * @param qrCodeHeight 二维码高度
     * @return bitmap
     */
    public static Bitmap generateQrCode(String content,int qrCodeWidth,int qrCodeHeight){
        Bitmap bitmap=null;
        Map<EncodeHintType,Object> hints=new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN,1);
        try {
            BitMatrix matrix=new MultiFormatWriter().
                    encode(content, BarcodeFormat.QR_CODE,qrCodeWidth,qrCodeHeight,hints);
            bitmap=bitMatrixToBitmap(matrix);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    private static Bitmap bitMatrixToBitmap(@NonNull BitMatrix matrix){
        final int width=matrix.getWidth();
        final int height=matrix.getHeight();
        Bitmap bitmap=Bitmap.createBitmap(width,height, Bitmap.Config.RGB_565);
        int[] rawData = new int[width * height];
        int color;
        for(int i=0;i<width;i++){
            for(int j=0;j<height;j++){
                color=0xFFFFFFFF;//背景色
                if(matrix.get(i,j)){
                    color=0xFF000000;//前景色
                }
                rawData[i+(j*width)]=color;
            }
        }
        bitmap.setPixels(rawData,0,width,0,0,width,height);
        return bitmap;
    }

}
